package com.qfedu.knowledge.handle;

import com.alibaba.fastjson.JSONObject;
import com.qfedu.knowledge.config.JwtConfig;
import com.qfedu.knowledge.dao.UserDao;
import com.qfedu.knowledge.entity.vo.ResultVO;
import com.qfedu.knowledge.entity.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName MyAuthenticationSucess
 * @Author ykx
 * @Date 2024/4/20 7:35
 * @Version 1.0
 */

@Component
public class MyAuthenticationSuccessHandle implements AuthenticationSuccessHandler {

    @Autowired
    private UserDao userDao;

    @Autowired
    private JwtConfig jwtConfig;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        // 获取当前用户名
        User user = (User) authentication.getPrincipal();

        // 根据用户名获取用户
        UserVO userVO = userDao.getUserByName(user.getUsername());
        userVO.setToken(jwtConfig.createToken(userVO.getUsername()));
        outputStream.write(JSONObject.toJSONString(ResultVO.success(userVO)).getBytes());
        outputStream.flush();
        outputStream.close();

    }
}
